using Microsoft.Extensions.Caching.Distributed;
using net_work.Common.Result;
using net_work.Common.Utils;
using net_work.IService.ISystem;

namespace net_work.Service.System;

public class CaptchaService(IDistributedCache cache) : ICaptchaService
{
    public async Task<CaptchaResult> GenerateCaptcha()
    {
        // 生成5位随机验证码
        var captchaCode = CaptchaUtils.GenerateRandomCode(5);
        // 验证码唯一标识
        var captchaId = Guid.NewGuid().ToString();

        // 将验证码存入 Redis，有效期为3分钟
        await cache.SetStringAsync($"Login:Captcha:Captcha_{captchaId}", captchaCode,
            new DistributedCacheEntryOptions
            {
                AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(3)
            });

        // 生成验证码图片
        var captchaImage = CaptchaUtils.GenerateCaptchaImage(captchaCode);

        // 将图片转为 Base64 字符串
        var base64Image = Convert.ToBase64String(captchaImage);

        // 返回 JSON 包含 CaptchaId 和 图片的 Base64 编码
        return new CaptchaResult { CaptchaId = captchaId, Base64Image = base64Image };
    }
}